package com.xtravel.discovery.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView;
import android.widget.GridView;
import android.widget.TextView;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.bitmap.PauseOnScrollListener;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import java.util.ArrayList;
import java.util.List;
import com.xtravel.R;
import com.xtravel.common.adapter.BaseDataAdapter;
import com.xtravel.common.database.dto.DtoBase;
import com.xtravel.common.widget.TweetImageView;
import com.xtravel.discovery.adapter.LiveTalentListAdapter;
import com.xtravel.discovery.api.LiveRequest;
import com.xtravel.discovery.dto.TalentDto;

public class LiveDetailActivity extends Activity {
    private Context context;

    @ViewInject(R.id.live_detail_textCaption)
    private TextView liveNameView;

    @ViewInject(R.id.live_item_cover)
    private TweetImageView liveCover;

    @ViewInject(R.id.talent_list)
    private GridView talentList;

    private BaseDataAdapter talentAdapter;
    private BitmapUtils bitmapUtils;
    private boolean isLatest;
    private View footerView;
    private TextView tvFooterText;
    private LiveRequest apiRequest = new LiveRequest();
    private Bundle liveData;
    /**
     * 是否正在加载数据，如果正在加载，则不进行加载，如果没有，则加载，
     * 用于用户数滑动列表
     */
    private Boolean isRefreshing = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.context = this;
        this.bitmapUtils = new BitmapUtils(this);
        setContentView(R.layout.live_item_detail);
        ViewUtils.inject(this);
        liveData = this.getIntent().getExtras();
        initGridView();
        showLiveInfo();
    }

    @Override
    protected void onStart() {
        super.onStart();
        this.getData(true);
    }

    private void showLiveInfo(){
        this.liveNameView.setText(liveData.getString("liveName"));
        this.liveCover.setImageUrl(this.bitmapUtils, liveData.getString("liveCover"));
    }

    private void initGridView() {
        this.footerView = View.inflate(context, R.layout.footer_tweet, null);
        this.footerView.setVisibility(View.GONE);
        this.tvFooterText = (TextView) footerView.findViewById(R.id.tvFooterText);
        this.talentAdapter = new LiveTalentListAdapter(this.context, bitmapUtils, new ArrayList<TalentDto>());
        this.talentList.setAdapter(talentAdapter);
        talentList.setOnScrollListener(new PauseOnScrollListener(bitmapUtils, true, true, new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem + visibleItemCount + 3 > totalItemCount && firstVisibleItem > 0) {
                    getData(false);
                }
            }
        }));
    }

    @OnClick(R.id.back_live_item_detail)
    public void onBack(View view) {
        this.finish();
    }

    @OnClick(R.id.talentPanel)
    public void onPlay(View view){
        boolean isLive = liveData.getBoolean("isLive", false);
//        Intent intent = new Intent(context, isLive ? ViewLiveMediaActivity.class : ViewRecordMediaActivity.class);
//        intent.putExtras(liveData);
//        context.startActivity(intent);
    }

    private void getData(boolean latest) {
        this.isLatest = latest;
        if (!this.isLatest) {
            if (isRefreshing) {
                return;
            }
            isRefreshing = true;
        }

        if (this.isLatest) {
            if (talentAdapter.getCount() > 0) {
                this.talentList.setBackgroundResource(R.color.transparant);
            }

            talentAdapter.notifyDataSetChanged();
        }

        Long sinceId = 0L, maxId = 0L;
        if (isLatest) {
            sinceId = talentAdapter.getMaxId();
        } else {
            maxId = talentAdapter.getMinId();
        }

        new AsyncTask<Long, Void, List<TalentDto>>() {
            @Override
            protected List<TalentDto> doInBackground(Long... params) {
                return apiRequest.getRelativeTalents(liveData.getInt("id"));
            }

            @Override
            protected void onPostExecute(List<TalentDto> records) {
                super.onPostExecute(records);
                Message msg = new Message();
                msg.obj = records;
                handler.sendMessage(msg);
            }
        }.execute(sinceId, maxId);
    }

    private android.os.Handler handler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            List<DtoBase> records = (List<DtoBase>) msg.obj;
            List<DtoBase> newItems = new ArrayList<DtoBase>();
            for (DtoBase item : records) {
                boolean exist = talentAdapter.isExist(item);
                if (!exist)
                    newItems.add(item);
            }

            if(newItems.size() > 0) {
                if (isLatest)
                    talentAdapter.addRangeAtBegin(newItems);
                else
                    talentAdapter.addRangeAtEnd(newItems);

                talentAdapter.notifyDataSetChanged();
            }

            if (!isLatest) {
                isRefreshing = false;
            }

            if (talentAdapter.getCount() == 0) {
                talentList.setBackgroundResource(R.drawable.no_data);
                return;
            } else {
                talentList.setBackgroundResource(R.color.transparant);
            }

            if (newItems != null && newItems.size() == 0 && !isLatest) {
                footerView.setVisibility(View.VISIBLE);
                tvFooterText.setText(R.string.str_no_data);
            }
        }
    };
}
